package cn.leonis.leetcode;

import java.util.Arrays;

/**
 * @author Tobi
 * @time 2021-12-09 11:22 PM
 * leetcode977
 * 题目描述：有序数组的平方
 */
public class SquareOfSortedArraySolution {

    /**
     * 解法一：直接排序
     * @param nums
     * @return
     */
    public int[] sortedSquares(int[] nums) {
        int[] result = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            result[i] = nums[i] * nums[i];
        }
        Arrays.sort(result);

        return result;
    }

    /**
     * 解法二：双指针
     * @param nums
     * @return
     */
    public int[] sortedSquares2(int[] nums) {
        int len = nums.length;
        int[] result = new int[len];
        for (int i = 0, j = len - 1, pos = len - 1; i <= j;) {
            if (nums[i] * nums[i] > nums[j] * nums[j]) {
                result[pos] = nums[i] * nums[i];
                ++i;
            }else {
                result[pos] = nums[j] * nums[j];
                --j;
            }
            --pos;
        }

        return result;
    }
}
